package huawei;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 字符串化繁为简
 */
public class Q98 {



    public static void main(String[] args) {

        String s = "(abd)demand(fb)()for";
//        String s = "()abcdefgAC(a)(Ab)(C)";

        List<Set<Character>> all = new ArrayList<Set<Character>>();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                Set<Character> set = new HashSet<>();
                for (int j = i + 1; j < s.length(); j++) {
                    if (s.charAt(j) == ')') {
                        i = j;
                        break;
                    } else {
                        set.add(s.charAt(j));
                    }
                }

                if (set.size() > 0) {
                    all.add(set);
                }
            }
        }

        // 排一下顺序
        all.sort((e1, e2) -> e2.size() - e1.size() );

        Set<Character> set = new HashSet<>();
        if (all.size() > 0) {
            set.addAll(all.get(0));
        }


        for (int i = 1; i < all.size(); i++) {
            Set<Character> characters = all.get(i);
            for (Character character : characters) {
                if (set.contains(character) || set.contains((char)(character - 32)) || set.contains((char)(character + 32))) {
                    set.addAll(characters);
                    break;
                }
            }
        }

        System.out.println(set);

        Character swapChar = new ArrayList<>(set).get(0);

        StringBuilder sb = new StringBuilder();
        boolean in = false;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(' || s.charAt(i) == ')') {
                in = !in;
                continue;
            }

            if (!in) {
                sb.append(set.contains(s.charAt(i)) ? swapChar : s.charAt(i));
            }
        }

        System.out.println(sb);
    }
}
